<template>
  <el-dialog
    :visible.sync="dialog"
    title="权限分配"
    append-to-body
    width="600px"
    @open="open"
  >
    <div v-loading="treeLoading">
      <el-tree
        ref="tree"
        :data="tree"
        :props="props"
        accordion
        show-checkbox
        node-key="uuid"
      />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="save">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { role_bind_permission, permission_all, role_permission } from '@/api/system';
export default {
  name: 'PermissionDialog',
  data() {
    return {
      data: {},
      tree: [],
      loading: false,
      treeLoading: false,
      dialog: false,
      props: {
        children: 'children',
        label: 'permissionName'
      }
    };
  },
  created() {
    this.getTree();
  },
  methods: {
    async open() {
      try {
        this.treeLoading = true;
        const res = await role_permission(this.data.uuid, {
          uuid: this.data.uuid
        });
        const Ids = res.data.reduce((i, c) => {
          i.push(c.uuid);
          return i;
        }, []);
        this.$refs.tree.setCheckedKeys(Ids);
        this.treeLoading = false;
      } catch (error) {
        this.treeLoading = false;
        console.error(error);
      }
    },
    cancel() {
      this.dialog = false;
    },
    async getTree() {
      this.treeLoading = true;
      const res = await permission_all();
      this.tree = res.data;
      this.treeLoading = false;
    },
    async save() {
      try {
        this.loading = true;
        const role = {
          roleUuid: this.data.uuid,
          actionUuids: [
            ...this.$refs.tree.getCheckedKeys(),
            ...this.$refs.tree.getHalfCheckedNodes()
          ]
        };

        await role_bind_permission(role);
        this.$message({
          message: '保存成功',
          type: 'success'
        });
        this.loading = false;
        this.dialog = false;
      } catch (error) {
        console.error(error);
        this.loading = false;
      }
    }
  }

};
</script>
